package com.eco.fanliapp.taobao;

import com.alibaba.fastjson.JSON;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderController {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 拉取维权订单
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderCountType
     * @param orderQueryType
     * @return
     */
    @RequestMapping(value = "/taobao/order/orderrefunddetailsNew", method = RequestMethod.POST)
    public TbkScPunishOrderGetResponse orderrefunddetailsNew(String session, String startTime, @RequestParam(defaultValue = "1") long pageNo, @RequestParam(defaultValue = "1") long tkStatus ,
                                                        @RequestParam(defaultValue = "1")long orderCountType, @RequestParam(defaultValue = "create_time")String orderQueryType, @RequestParam(defaultValue = "1") long orderScene ) {
        TbkScPunishOrderGetRequest req = new TbkScPunishOrderGetRequest();
        TaobaoClient client = new DefaultTaobaoClient(Config.TAO_URL, Config.TAO_APPKEY, Config.TAO_APPSECRET);
        TbkScPunishOrderGetRequest.TopApiAfOrderOption obj1 = new TbkScPunishOrderGetRequest.TopApiAfOrderOption();
        obj1.setSpan(1200L);
//        obj1.setRelationId(2222L);
//        obj1.setTbTradeId(258897956183171983L);
//        obj1.setTbTradeParentId(258897956183171983L);
        obj1.setPageSize(100L);
        obj1.setPageNo(pageNo);
        obj1.setStartTime(StringUtils.parseDateTime(startTime));
//        obj1.setSpecialId(23132L);
//        obj1.setViolationType(1L);
//        obj1.setPunishStatus(1L);
        req.setAfOrderOption(obj1);


        try {
            TbkScPunishOrderGetResponse rsp = client.execute(req, session);
            return  rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 拉取维权订单
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderCountType
     * @param orderQueryType
     * @return
     */
    @RequestMapping(value = "/taobao/order/orderrefunddetails", method = RequestMethod.POST)
    public TbkRelationRefundResponse orderRefundDetails(String session, String startTime, @RequestParam(defaultValue = "1") long pageNo, @RequestParam(defaultValue = "1") long tkStatus ,
                                                        @RequestParam(defaultValue = "1")long orderCountType, @RequestParam(defaultValue = "create_time")String orderQueryType, @RequestParam(defaultValue = "1") long orderScene ) {
        TbkRelationRefundRequest req = new TbkRelationRefundRequest();
        TaobaoClient client = new DefaultTaobaoClient(Config.TAO_URL, Config.TAO_APPKEY, Config.TAO_APPSECRET);
        TbkRelationRefundRequest.TopApiRefundRptOption obj1 = new TbkRelationRefundRequest.TopApiRefundRptOption();
        obj1.setPageNo(pageNo);
        obj1.setPageSize(100L);
        obj1.setSearchType(1L);
        obj1.setRefundType(1L);
        obj1.setStartTime(StringUtils.parseDateTime(startTime));
        obj1.setBizType(orderScene);
        req.setSearchOption(obj1);

        try {
            TbkRelationRefundResponse rsp = client.execute(req);
            return  rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

//    /**
//     * 拉取订单
//     * @param session
//     * @param startTime
//     * @param pageNo
//     * @param tkStatus
//     * @param orderCountType
//     * @param orderQueryType
//     * @return
//     */
//    @RequestMapping(value = "/taobao/order/orderdetails", method = RequestMethod.POST)
//    public TbkScOrderGetResponse orderDetails(String session, String startTime, @RequestParam(defaultValue = "1") long pageNo, @RequestParam(defaultValue = "1") long tkStatus ,
//                                              @RequestParam(defaultValue = "1")long orderCountType, @RequestParam(defaultValue = "create_time")String orderQueryType, @RequestParam(defaultValue = "1") long orderScene ) {
//        TbkScOrderGetRequest req = new TbkScOrderGetRequest();
//        TaobaoClient client = new DefaultTaobaoClient(Config.TAO_URL, Config.TAO_APPKEY, Config.TAO_APPSECRET);
//        req.setFields("tb_trade_parent_id,tb_trade_id,num_iid,item_title,tk_status,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,relation_id,tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,special_id");
//        req.setStartTime(StringUtils.parseDateTime(startTime));
//        req.setSpan(1200L);
//        req.setPageNo(pageNo);
//        req.setPageSize(100L);
//        req.setTkStatus(tkStatus);
//        req.setOrderScene(orderScene);
//        req.setOrderCountType(orderCountType);
//        req.setOrderQueryType(orderQueryType);
//        try {
//            TbkScOrderGetResponse rsp = client.execute(req,session);
//
//            //如果有非法或过期的SessionKey参数，保存到缓存中3分钟
//            log.info("开始处理SessionKey是否失效=====start");
//            if(rsp.getSubMsg().contains("SessionKey非法")){
//                String SessionKey =(String)redisTemplate.opsForValue().get(session);
//                log.info("从redis中已经存在SessionKey:{}",SessionKey);
//                if(SessionKey == null || "".equals(SessionKey)  ){
//                    log.info("SessionKey的生效时间3分钟");
//                    redisTemplate.opsForValue().set("session",session, 180, TimeUnit.SECONDS);
//                }
//
//            }
//            log.info("开始处理SessionKey是否失效=========end");
//            return  rsp;
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 拉取订单
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @return
     */
    @RequestMapping(value = "/taobao/order/orderdetails2", method = RequestMethod.POST)
    public TbkOrderDetailsGetResponse orderDetails2(String startTime,String endTime, @RequestParam(defaultValue = "1") long pageNo, @RequestParam(defaultValue = "1") long tkStatus ,
                                               @RequestParam(defaultValue = "1") long orderScene ) {
        TaobaoClient client = new DefaultTaobaoClient(Config.TAO_URL, "26061253", "f21a42fbafd26358f6cad66335c47fa4");
        TbkOrderDetailsGetRequest req = new TbkOrderDetailsGetRequest();
        req.setQueryType(1L);
//        req.setPositionIndex("2222_334666");
        req.setPageSize(20L);
        req.setMemberType(2L);
        req.setTkStatus(tkStatus);
        req.setEndTime(endTime);
        req.setStartTime(startTime);
//        req.setJumpType(100L);
        req.setPageNo(pageNo);
        req.setOrderScene(orderScene);



        try {
            TbkOrderDetailsGetResponse rsp = client.execute(req);
            return  rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 拉取订单
     *
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @return
     */
    /**
     *
     * @param session
     * @param startTime
     * @param endTime
     * @param pageNo
     * @param tkStatus 淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
     * @param orderCountType  订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
     * @param orderQueryType 查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询  订单查询类型，创建时间“create_time”，或结算时间“settle_time”。当查询渠道或会员运营订单时，建议入参创建时间“create_time”进行查询
     * @param orderScene  订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，
     * @param positionIndex
     * @return
     */
    @RequestMapping(value = "/taobao/order/orderdetailsNew", method = RequestMethod.POST)
    public TbkScOrderDetailsGetResponse orderDetailsNew(String session, String startTime, String endTime, @RequestParam(defaultValue = "1") long pageNo
            , @RequestParam(defaultValue = "1") long tkStatus,@RequestParam(defaultValue = "2") long orderCountType
            ,@RequestParam(defaultValue = "1")String orderQueryType, @RequestParam(defaultValue = "1") long orderScene,
            String positionIndex) {

        TaobaoClient client = new DefaultTaobaoClient(Config.TAO_URL, Config.TAO_APPKEY, Config.TAO_APPSECRET);
        TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();
        req.setQueryType(Long.parseLong(orderQueryType));
//        req.setPositionIndex("2222_334666");
        req.setPageSize(100L);
//        req.setMemberType(orderCountType);
        req.setTkStatus(tkStatus);
        req.setEndTime(endTime);
        req.setStartTime(startTime);
//        req.setJumpType(100L);
        req.setPageNo(pageNo);
        req.setOrderScene(orderScene);
        req.setPositionIndex(positionIndex);


        try {
            TbkScOrderDetailsGetResponse rsp = client.execute(req, session);
            //如果有非法或过期的SessionKey参数，保存到缓存中3分钟
//            log.info("开始处理SessionKey是否失效=====start");
            if (rsp != null && rsp.getSubMsg() != null) {
                if (rsp.getSubMsg().indexOf("非法或过期的SessionKey参数") > -1 || (rsp.getSubMsg().contains("SessionKey") && rsp.getSubMsg().contains("非法"))) {
                    String sessionKey = (String) redisTemplate.opsForValue().get("session" + session);
                    log.info("从redis中已经存在SessionKey:{}", sessionKey);
                    if (sessionKey == null || "".equals(sessionKey)) {
                        log.info("从redis中已经存在SessionKey:" + sessionKey + "-->sessionKey的生效时间3分钟" + "rsp=" + JSON.toJSONString(rsp));
                        redisTemplate.opsForValue().set("session" + session, session, 300, TimeUnit.SECONDS);
                    }
                }
            }
//            log.info("开始处理SessionKey是否失效=========end");
            return rsp;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String args[]) {
        OrderController orderController = new OrderController();

//        TbkScPunishOrderGetResponse rep = orderController.orderrefunddetailsNew("6101028df8747496379de962531da27f8d041b2d6b1879f2972101538", "2019-08-21 14:30:00"
//                , 1, 12, 1, "1", 1
//
//        );
//        TbkOrderDetailsGetResponse rep = orderController.orderDetails2("2019-08-21 14:30:00", "2019-08-21 14:50:00", 1, 12, 1);
//
//        session：联盟session
//        startTime：查询开始时间
//        endTime：结束时间
//        pageNo：第几页
//        tkStatus：淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
//        orderCountType：  订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
//        orderQueryType：  查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
//        orderScene：  订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，
//        positionIndex： 需要分页的参数
        String ss = "Kiehl's科颜氏契尔氏特效高保湿乳液水滋润补水  比如搜索这个的，你们没有过滤iehl's中的'";
        System.out.println(ss);

        TbkScOrderDetailsGetResponse rep2 = orderController.orderDetailsNew("610221709924669a2691fb7c01c9813b9b0e2484439f76d2972101538",
                "2020-03-09 13:00:00", "2020-03-09 10:00:00", 1, 12,2L, "2", 1,null);
        log.info(JSON.toJSONString(rep2));

    }
}
